package cn.lg.soar.system.biz.modules.auth.service.impl;

import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.common.util.data.DataUtil;
import cn.lg.soar.core.model.DataScopeInfo;
import cn.lg.soar.database.base.service.impl.BaseServiceImpl;
import cn.lg.soar.system.biz.config.SystemCacheKey;
import cn.lg.soar.system.biz.modules.auth.entity.DataRule;
import cn.lg.soar.system.biz.modules.auth.entity.DataScope;
import cn.lg.soar.system.biz.modules.auth.entity.Resource;
import cn.lg.soar.system.biz.modules.auth.mapper.DataRuleMapper;
import cn.lg.soar.system.biz.modules.auth.mapper.DataScopeMapper;
import cn.lg.soar.system.biz.modules.auth.mapper.ResourceMapper;
import cn.lg.soar.system.biz.modules.auth.service.IResourceService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Resource服务层实现
 * 数据源
 * @author luguoxiang
 * @since 2022-04-30
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@ConditionalOnProperty(name = "lg.database.enabled-data-permission", havingValue = "true", matchIfMissing = true)
public class ResourceServiceImpl extends BaseServiceImpl<ResourceMapper, Resource> implements IResourceService {

    @Autowired
    private DataRuleMapper dataRuleMapper;
    @Autowired
    private DataScopeMapper dataScopeMapper;

    @Override
    public boolean save(Resource entity) {
        return super.save(entity);
    }

    @Override
    public boolean updateById(Resource entity) {
        return super.updateById(entity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeByIds(Collection<?> list) {
        if (DataUtil.isEmpty(list)) {
            return true;
        }
        AssertUtil.isTrue(super.removeByIds(list), "操作失败");
        List<Long> ruleIds = dataRuleMapper.selectList(
                Wrappers.<DataRule>lambdaQuery()
                        .select(DataRule::getId)
                        .in(DataRule::getResourceId, list)
        ).stream()
                .map(DataRule::getId)
                .collect(Collectors.toList());
        dataRuleMapper.deleteByIds(ruleIds);
        dataScopeMapper.delete(
                Wrappers.<DataScope>lambdaQuery()
                        .in(DataScope::getResourceId, list)
        );
        return true;
    }

    @Override
    public Resource getByCode(String code) {
        return getOne(
                Wrappers.<Resource>lambdaQuery()
                        .eq(Resource::getCode, code)
        );
    }

    @Override
    public List<String> codesByIds(Collection<Long> ids) {
        if (DataUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return listObjs(
                Wrappers.<Resource>lambdaQuery()
                        .select(Resource::getCode)
                        .in(Resource::getId, ids),
                Object::toString
        );
    }

    public void removeCacheByResourceId(Collection<Long> resourceIds) {
        Cache cache = cacheManager.getCache(SystemCacheKey.RESOURCE_TO_RULEMAP);
        if (cache != null) {
            List<String> codes = codesByIds(resourceIds);
            for (String code : codes) {
                cache.evict(code);
            }
        }
    }

    @Override
    public void scanDataScopeGenPermit(Collection<DataScopeInfo> values) {
        List<Resource> list = list(
                Wrappers.<Resource>lambdaQuery()
                        .select(Resource::getId, Resource::getCode, Resource::getName)
        );
        Map<String, Resource> map = list.stream().collect(Collectors.toMap(Resource::getCode, x -> x));
        List<Resource> insets = new ArrayList<>(values.size());
        List<Resource> updates = new ArrayList<>(values.size());
        for (DataScopeInfo x : values) {
            Resource resource = map.get(x.getCode());
            if (resource == null) {
                resource = new Resource();
                resource.setCode(x.getCode());
                resource.setName(x.getName());
                resource.setDisabled(false);
                insets.add(resource);
            } else if (!Objects.equals(x.getName(), resource.getName())) {
                resource.setName(x.getName());
                updates.add(resource);
            }
        }
        // 入库
        saveBatch(insets);
        updateBatchById(updates);
    }

    @CacheEvict(value = SystemCacheKey.RESOURCE_TO_RULEMAP, allEntries = true)
    @Override
    public void clearCache() {}

}
